﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;
using MapReduceLib.Contracts;
using System.IO;
using MapReduceLib.DataModel;
using System.Configuration;

namespace ManagerApp
{
    public partial class MainForm : Form
    {
        private IJobManager jobManager;
        private ITaskTracker taskTracker;
        private BindingSource jobBindingSource;

        public MainForm()
        {
            InitializeComponent();
            jobBindingSource = new BindingSource();
            jobBindingSource.DataSource = Enumerable.Empty<Job>();

            lBoxAvailableJobs.DisplayMember = "JobName";
            lBoxAvailableJobs.ValueMember = "JobId";
            lBoxAvailableJobs.DataSource = jobBindingSource;
            tBoxJobId.DataBindings.Add("Text", jobBindingSource, "JobId", true, DataSourceUpdateMode.OnPropertyChanged);
            tBoxJobVersion.DataBindings.Add("Text", jobBindingSource, "JobVersion", true, DataSourceUpdateMode.OnPropertyChanged);

            try
            {
                InitializeServices();
                UpdateAvailableJobList();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Error during init", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void InitializeServices()
        {
            EndpointAddress myEndpoint = new EndpointAddress(string.Format("net.tcp://{0}/JobManager/", ConfigurationManager.AppSettings["MasterNodeAddress"]));
            ChannelFactory<IJobManager> scf = new ChannelFactory<IJobManager>(new NetTcpBinding(SecurityMode.None), myEndpoint);
            jobManager = scf.CreateChannel();

            myEndpoint = new EndpointAddress(string.Format("net.tcp://{0}/TaskTracker/", ConfigurationManager.AppSettings["MasterNodeAddress"]));
            ChannelFactory<ITaskTracker> taskTrackerFactory = new ChannelFactory<ITaskTracker>(new NetTcpBinding(SecurityMode.None), myEndpoint);
            taskTracker = taskTrackerFactory.CreateChannel();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog openDialog = new OpenFileDialog();
            openDialog.Filter = "Zip Files (.zip)|*.zip|All Files (*.*)|*.*";

            if (openDialog.ShowDialog() == DialogResult.OK)
            {
                txtArchivePath.Text = openDialog.FileName;
            }
        }

        private void btbDeploy_Click(object sender, EventArgs e)
        {
            try
            {
                string jobId = jobManager.EnqueueJob(File.ReadAllBytes(txtArchivePath.Text));
                MessageBox.Show(string.Format("Successfully deployed job with ID {0}", jobId), "Notification", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error during deploy", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (tabControl1.SelectedIndex)
            {
                case 0: //Run Job;
                    UpdateAvailableJobList();
                    break;

                case 1: //Deploy job;
                    break;

                case 2: //Status;
                    break;
            }
        }

        private void UpdateAvailableJobList()
        {
            jobBindingSource.DataSource = jobManager.GetAvailableJobs();
            jobBindingSource.ResetBindings(false);

            btnStartJob.Enabled = lBoxAvailableJobs.Items.Count > 0;
        }

        private void btnStartJob_Click(object sender, EventArgs e)
        {
            taskTracker.RunJob(lBoxAvailableJobs.SelectedValue as string);
        }
    }
}
